﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class MemberReferenceRule : ILRule<MemberReferenceHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public EntityHandle Parent { get; }

        public byte[] Signature { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        [ILInfo(true)]
        public MemberReferenceKind Kind { get; }

        public MemberReferenceRule(
            EntityHandle parent,
            string name,
            byte[] signature)
            : base()
        {
            Parent = parent;
            Name = name;
            Signature = signature;
        }

        public MemberReferenceRule(MetadataReader reader, MemberReferenceHandle memberReferenceHandle)
            : base(reader)
        {
            MemberReference memberReference = reader.GetMemberReference(memberReferenceHandle);
            Name = reader.GetString(memberReference.Name);
            Parent = memberReference.Parent;
            Signature = reader.GetBlobBytes(memberReference.Signature);
            CustomAttributes = memberReference.GetCustomAttributes();
            Kind = memberReference.GetKind();
        }

        public override MemberReferenceHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddMemberReference(
                parent: Parent,
                name: Name == null ? default : builder.GetOrAddString(Name),
                signature: Signature == null ? default : builder.GetOrAddBlob(Signature));
        }
    }
}